<template>
	<view style='padding-top: 5vh;'>
		<view v-if='hadPhone'>
			<view style='color:#909399;text-align: center;padding:10px;margin-bottom:30px'>请输入车牌号码查询停车情况</view> 
			<view>
				<view class="cu-form-group">
					<view class="title" @tap="plateShow = true">车牌号</view>
					<input placeholder="请点此输入" disabled="inputDisabled" @tap="plateShow = true" v-model.trim="plateNo" />
					<plate-input v-if="plateShow" :plate="plateNo" @export="setPlate" @close="plateShow = false" />
				</view>
			</view>
			<view v-if='plateNos && plateNos.length > 0' class='container'>
				<text v-for='item in plateNos' class='box' @click='setCarNumber(item)'>
					{{item}}
				</text>
			</view>
			<view v-if='order == ""' style='margin-top:20px'>
				<view style='color:#fff;background-color: #2979ff;margin: 20px;border-radius: 20px;text-align: center;padding:10px;' @click='submit'>查询</view>
			</view>
			<view v-else style='padding:10px;color:#909399'>
				<view>
					车牌<text class='ip-data'>【{{order.carNo}}】</text>
				</view> 
				<view>
					入场时间：<text class='ip-data'>{{order.startTime}}</text>
				</view> 
				<view>
					停车时长：<text class='ip-data'>{{(order.serviceTime/3600).toFixed(1)}}</text>小时,应缴费<text class='ip-data'>{{order.totalFee}}</text>元
				</view>
				<view>
					您当前积分为{{balance}}，每{{pointFeeHours}}积分可以抵扣1小时
				</view> 
				<!-- 减免时长大于停车时长，就不需要支付 -->
				<view v-if='freeHours > (order.serviceTime/3600) || order.totalFee == 0'> 
					<view style='color:#fff;background-color: #19be6b;margin: 20px;border-radius: 20px;text-align: center;padding:10px;' >无需支付</view>
				</view>
				<view v-else style='margin-top:30px;width:100%;'>
					<view>
						<view style='width:50%;float:left;'>
							<view style='color:#fff;background-color: #2979ff;margin: 10px;border-radius: 20px;text-align: center;padding:10px;' @click='pay'>支付费用</view> 
						</view>
						<view style='width:50%;float:left;'>
							<view style='color:#fff;background-color: #19be6b;margin: 10px;border-radius: 20px;text-align: center;padding:10px;' @click='pointPay'>积分抵扣</view>
						</view>
					</view>
				</view> 
			</view>
			<view v-if='bannerImages != ""'>
				<img @click='toUrl(bannerImages.link)' :src='bannerImages.image' class="responsive-image">
			</view>
		</view>
		<view v-else style='padding-top: 20vh'>
			<view style='padding:0px 20px'>
				<view style='text-align: center;color:#909399;pdding:10px'>
					请先登录
				</view>
				<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" style='border-radius: 20px;background-color: #19be6b;color:#fff'>手机号码登录</button>
			</view>
		</view>
	</view>
</template>

<script>
import plateInput from '@/components/uni-plate-input/uni-plate-input.vue';
import wechatPay from '@/utils/wechat-pay.js'
export default {
	components: {
		plateInput
	},
	data() {
		return {
			plateNo: '',
			plateShow: false,
			inputDisabled: true,
			show: true,
			hadPhone: false,
			order: '',
			plateNos: [],
			balance: 0,
			pointFeeHours: 0,
			freeHours: 0,
			bannerImages: ''
		};
	},
	onShow() {
		this.request.get(`api/balances`).then((res) => {
			this.balance = res.data.point
		})
	},
	onLoad(options) {
		let api_token = uni.getStorageSync('api_token')
		if(api_token == ''){
			this.wxLogin()
		}else{
			this.getPhone()
			this.getBanner()
		}
		this.request.get(`api/options/REDUCE_POINTS_PER_HOUR`).then((res) => {
			console.log('12',res.data)
			this.pointFeeHours = res.data.value
		})
		// 传车牌的，直接查询
		if(typeof(options.plateNo) != 'undefined'){
			this.plateNo = options.plateNo
			this.submit()
		}
	},
	methods: {
		getBanner() {
			this.request.get(`api/albums/2`).then((res) => {
				if(res.data && res.data.pictures.length > 0)
				this.bannerImages = res.data.pictures[0]
			})
		},
		pointPay(){
			let data = {
				hours: Math.ceil(this.order.serviceTime/3600),
				vehicleNo: this.plateNo.trim(),
				parkCode: 'p220649759'
			}
			console.log(data)
			uni.showLoading()
			this.request.post(`api/parking-discounts`,data).then((res) => {
				uni.hideLoading()
				uni.showModal({
					title: '',
					content: '减免成功！',
					showCancel: false,
					success: () => {
						uni.switchTab({
							url: '/pages/index/index'
						})
					}
				})
			}).catch((err) => {
				uni.hideLoading()
			})
		},
		toUrl(page){
			if(page){
				uni.navigateTo({
					url: page
				})
			}
		},
		// 支付费用，先获取当前车牌，然后再查询时间
		pay(){
			this.request.post(`api/vehicle-orders`,{vehicleNo: this.plateNo.trim()}).then((res) => {
				let invoiceId = res.data.invoice.id
				wechatPay(invoiceId).then((res) => {
					uni.hideLoading()
					uni.showModal({
						title: '',
						content: '支付成功，请在15分钟内离场！',
						showCancel: false,
						success: () => {
							uni.switchTab({
								url: '/pages/index/index'
							})
						}
					})
				}).catch((err) => {
					uni.hideLoading()
					uni.showModal({
						title: '',
						content: '支付失败，请重试',
						showCancel: false,
						success: () => {}
					})
				})
			})
		},
		setCarNumber(number){
			this.plateNo = number
		},
		submit(){
			// 查询车牌的停车时长
			if(this.plateNo == ''){
				uni.showToast({
					title: '请输入车牌号码！',
					icon: 'none'
				})
				return
			}
			uni.showLoading()
			this.request.post(`api/parkings/create-pay-order-by-vehicle-no`,{
				store: 1,
				vehicleNo: this.plateNo.trim(),
				parkCode: 'p220649759'
			}).then((res) => {
				uni.hideLoading()
				console.log(res.data)
				if(res.data[0].attributes.retmsg != ''){
					uni.showToast({
						title: res.data[0].attributes.retmsg,
						icon: 'none'
					})
					return
				}
				this.order = res.data[0].attributes
				// 如果自己的车牌列表无该车牌，就记录
				if(this.plateNos.indexOf(this.plateNo.trim()) === -1){
					this.plateNos.push(this.plateNo.trim())
					this.request.put(`api/user-profile`,{
						vehicleNos: this.plateNos
					})
				}
			})
		},
		setPlate(plate) {
			if (plate.length >= 7) this.plateNo = plate;
			this.plateShow = false;
		},
		wxLogin() {
			let _this = this
			uni.login({
				success(result) {
					console.log(111, result)
					let code = result.code
					_this.request.get(`wechat/mini/login`, {
						code
					}).then((res) => {
						console.log('login', res)
						const token = res.data.token
						uni.setStorageSync('api_token', token)
						_this.getPhone()
						_this.getBanner()
					})
				}
			})
		},
		getPhone(){
			this.request.get(`api/user`,{
				'@expands': `['entity.profile']`
			}).then((res) => {
				console.log(res.data)
				if (res.data.profile.__metadata && res.data.profile.__metadata.vehicleNos) {
					this.plateNos = res.data.profile.__metadata.vehicleNos
				}
				if(res.data.profile && res.data.profile.__metadata && res.data.profile.__metadata.phone){
					this.hadPhone = true
				}
			})
		},
		getPhoneNumber(e) {
			let _this = this
			if (typeof(e.detail.iv) == 'undefined') {
				uni.showToast({
					title: '获取失败，请重试',
					icon: 'none'
				})
				return
			} else {
				uni.showLoading()
				uni.login({
					provider: "weixin",
					success: function(res) {
						let data = {
							code: res.code
						}
						_this.request.get("wechat/mini/login", data).then((res) => {
							uni.setStorageSync('api_token', res.data.token);
							if (res.data.data.session_key) {
								let data = {
									sessionKey: res.data.data.session_key,
									iv: e.detail.iv,
									encryptedData: e.detail.encryptedData,
								}
								_this.request.post(`wechat/decrypt-data`, data).then((res) => {
									_this.phone = res.data.phoneNumber
									console.log('phone', res);
									//更新手机号码
									_this.request.put(`api/user-profile`, {
										phone: res.data.phoneNumber
									}).then((res) => {
										uni.hideLoading()
										_this.hadPhone = true
									})
								})
							} else {
								uni.hideLoading()
								uni.showToast({
									title: '获取手机号码失败！',
									icon: 'none'
								})
							}
						})
					},
				});
			}
		}
	} 
};
</script>

<style>
.cu-form-group {
	border-top: 1px solid #eee;
	border-bottom: 1px solid #eee;
	background-color: #ffffff;
	padding: 1upx 30upx;
	display: -webkit-box;
	display: -webkit-flex;
	display: -ms-flexbox;
	display: flex;
	align-items: center;
	min-height: 100upx;
	justify-content: space-between;
}

.ip-data{
	color:#303133;
	font-weight: bold;
}

.car-number{
	margin:30px 5px;
	padding:5px 10px;
	background-color: #2979ff;
	font-size: 14px;
	color:#fff;
	border-radius: 5px;
	width:30%;
	display: block; /* 让span元素作为块级元素显示 */
	overflow-wrap: break-word; /* 允许在长单词内部换行 */
}
.container {
  display: flex;
  flex-wrap: wrap;
}
 
.box {
  margin: 1%; /* 可以根据需要调整间距 */
  padding: 10px; /* 内边距 */
  border: 1px solid #606266; /* 边框 */
  color: #606266;
  border-radius: 3px;
  text-align: center;
  /* 以下是样式，根据需要自定义 */
  flex: 0 0 auto; /* 不伸缩，固定宽度，根据内容自动换行 */
  min-width: 25%; /* 最小宽度 */
}

.responsive-image {
  width: 100%; /* 或者指定一个具体的宽度 */
  object-fit: scale-down; /* 当图片宽/高超过容器宽/高时，等比缩放 */
}
</style>
